package com.zhitong.ztblog.controllers;


import com.zhitong.ztblog.entity.Sort;
import com.zhitong.ztblog.services.ISortService;
import com.zhitong.ztblog.utils.AjaxResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class SortContro {

    @Autowired
    private ISortService sortService;

    @GetMapping("/randSorts")
    public AjaxResponse getRandSorts(){
        Sort[] sorts = sortService.findByRand();
        AjaxResponse ajaxResponse=new AjaxResponse();
        ajaxResponse.setMessage("请求成功");
        ajaxResponse.setData(sorts);
        return ajaxResponse;
    }

    @GetMapping("/sorts")
    public AjaxResponse getSorts(){
        Sort[] all = sortService.findAll();
        int sortNum = sortService.findSortNum();
        Map<String,Object> map=new HashMap<>();
        map.put("sorts",all);
        map.put("sortNum",sortNum);
        AjaxResponse success = AjaxResponse.success(map);
        return success;
    }

    @GetMapping("/sort/{id}")
    public AjaxResponse getSrotById(@PathVariable(name = "id")int id){
        Sort sort = sortService.findById(id);
        AjaxResponse success = AjaxResponse.success(sort);
        return success;
    }

    @DeleteMapping("/sort/{id}")
    public AjaxResponse delSrotById(@PathVariable(name = "id")int id){
        sortService.delSortById(id);
        AjaxResponse success = AjaxResponse.success();
        return success;
    }

    @PostMapping("/sort")
    public AjaxResponse insertSort(@RequestBody Sort sort){
        int sortByName = sortService.findSortByName(sort);
        if (sortByName>0){
            AjaxResponse ajaxResponse=new AjaxResponse();
            ajaxResponse.setCode(500);
            ajaxResponse.setMessage("该分类已经存在!");
            return ajaxResponse;
        }else {
            sortService.insertSort(sort);
            AjaxResponse success = AjaxResponse.success();
            success.setMessage("添加成功");
            return success;
        }
    }

}
